<template>
  <div id="userManagePage">
    <a-input-search
      style="max-width: 400px; margin-bottom: 20px"
      v-model:value="username"
      placeholder="输入要搜索的用户名"
      enter-button="搜索"
      size="large"
      @search="onSearch"
    />

    <a-table :columns="columns" :data-source="data">
      <!--      自定义表格列-->
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'avatar'">
          <a-image :src="record.avatar" width="100px" />
        </template>
        <template v-else-if="column.key === 'tags'">
          <span>
            <a-tag
              v-for="tag in record.tags"
              :key="tag"
              :color="tag === 'loser' ? 'volcano' : tag.length > 5 ? 'geekblue' : 'green'"
            >
              {{ tag.toUpperCase() }}
            </a-tag>
          </span>
        </template>
        <template v-else-if="column.key === 'action'">
          <span>
            <a-button danger @click="doDelete(record.id)">删除</a-button>
          </span>
        </template>
      </template>
    </a-table>
  </div>
</template>
<script lang="ts" setup>
import { SmileOutlined, DownOutlined } from '@ant-design/icons-vue'
import { ref } from 'vue'
import { deleteUser, searchUsers } from '@/api/user.ts'
import { message } from 'ant-design-vue'

const columns = [
  {
    title: 'id',
    dataIndex: 'id',
  },
  {
    title: '用户名',
    dataIndex: 'username',
  },
  {
    title: '头像',
    dataIndex: 'avatar',
  },
  {
    title: '操作',
    key: 'action',
  },
]

const data = ref([])
const username = ref('')
const onSearch = () => {
  fetchData(username.value)
}

//删除用户
const doDelete = async (id: string) => {
  if (!id) {
    return
  }
  const res = await deleteUser(id)
  if (res.data.code === 1) {
    message.success(res.data.msg)
    // 删除成功后重新获取用户数据，添加 await 等待获取数据完成
    await fetchData(username.value)
  } else {
    message.error(res.data.msg)
  }
}

//定义从后台获取用户数据
const fetchData = async (username = '') => {
  const res = await searchUsers(username)
  if (res.data.data) {
    data.value = res.data.data
  } else {
    message.error('获取数据失败')
  }
}
//调用方法
fetchData('')
</script>
